#!/usr/bin/env pwsh

# 保存原始工作目录
$originalDir = Get-Location

# 获取命令行参数，默认为启动模式
if ($args.Count -gt 0) {
    $mode = $args[0].ToLower()
} else {
    $mode = "start"
}

# Redis Service Script
if ($mode -eq "start") {
    Write-Host "Starting Redis Service..." -ForegroundColor Yellow
    
    # 确保 Redis 数据目录存在的函数
    function Ensure-DirectoryExists {
        param (
            [string]$directoryPath
        )
        
        # 检查目录是否存在
        if (-not (Test-Path -Path $directoryPath -PathType Container)) {
            Write-Host "Creating directory: $directoryPath" -ForegroundColor Yellow
            # 创建目录（包括所有必要的父目录）
            New-Item -Path $directoryPath -ItemType Directory -Force | Out-Null
            Write-Host "Directory created successfully." -ForegroundColor Green
        } else {
            Write-Host "Directory already exists: $directoryPath" -ForegroundColor Green
        }
    }
    
    # 设置 Redis 数据目录路径
    $mountDirectory = "$HOME\docker_data\redis\data"
    
    # 确保数据目录存在
    Ensure-DirectoryExists -directoryPath $mountDirectory

    # Check and create server_network if it doesn't exist
    if (-not (docker network ls | Select-String -Pattern "server_network")) {
        Write-Host "Creating server_network network..." -ForegroundColor Yellow
        docker network create --driver bridge server_network 2>$null
    }

    docker-compose -f .\server\2-docker-compose-redis.yml up -d
    Write-Host "Redis Service started successfully!" -ForegroundColor Green
    Write-Host "You can check status with: docker-compose -f .\server\2-docker-compose-redis.yml ps" -ForegroundColor White
    Write-Host "To stop the service, run: ./02start_redis.ps1 stop" -ForegroundColor White
} elseif ($mode -eq "stop") {
    Write-Host "Stopping Redis Service..." -ForegroundColor Yellow
    docker-compose -f .\server\2-docker-compose-redis.yml stop
    Write-Host "Redis Service stopped successfully!" -ForegroundColor Green
    Write-Host "To start the service again, run: ./02start_redis.ps1 start" -ForegroundColor White
} else {
    Write-Host "Invalid mode. Please use 'start' or 'stop'." -ForegroundColor Red
    Write-Host "Example: ./02start_redis.ps1 start" -ForegroundColor White
    Write-Host "Example: ./02start_redis.ps1 stop" -ForegroundColor White
    exit 1
}

# 恢复原始工作目录
Set-Location -Path $originalDir